package com.yj.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;

import com.yj.dao.BaseDao;

@Repository("baseDao")
@Lazy(true)
public class BaseDaoImpl<T> implements BaseDao<T> {

	@SuppressWarnings("rawtypes")
	private Class clazz;
	
	@Resource
	private SessionFactory sessionFactory;
	
	@SuppressWarnings("rawtypes")
	public BaseDaoImpl() {
		ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
		clazz = (Class)type.getActualTypeArguments()[0];
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}



	@Override
	public void save(T t) {
        getSession().save(t);
	}

	@Override 
	public void update(T t) {
        getSession().update(t);
	}

	@Override
	public void delete(Integer id) {
        String hql = "delete " + clazz.getSimpleName() + " as c where c.id=:id";
        getSession().createQuery(hql).setParameter("id", id).executeUpdate();
	}

	@SuppressWarnings("unchecked")
	@Override
	public T get(Integer id) {
		return (T)getSession().get(clazz, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> query() {
		String hql = "from " + clazz.getSimpleName();
		return getSession().createQuery(hql).list();
	}
}
